import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/bill/widgets/select_renter.dart";
import "package:ct_pa_majordomo/pages/bill/widgets/show_multi_date_picker.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/widgets/bottom_sheet/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:image_picker/image_picker.dart";

class Accounting extends StatefulWidget {
  const Accounting({super.key});

  @override
  State<StatefulWidget> createState() => _AccountingState();

}

class _AccountingState extends State<Accounting> {
  Widget _required = Text("*", style: TextStyle(color: ThemeVars.colorError),);
  int _collectedTarget = 0;
  List<XFile>? _imageFile;
  late ImagePicker _imagePicker;
  Map _params = {
    "collectedTarget": 0,
    "renterId": null,
    "renterName": "",
    "contacts": "",
    "name": "",
    "money": "",
    "inoutFlag": null,
    "inoutFlagName": "",
    "billStartDate": DateTools.formatYMD(DateTime.now()),
    "billEndDate": DateTools.formatYMD(DateTime.now()),
    "noticeDate": DateTools.formatYMD(DateTime.now()),
    "remark": "",
  };
  List _inoutFlagList = [{
    "name": "收入",
    "value": 0,
  }, {
    "name": "支出",
    "value": 1,
  }];

  Widget _radio({
    required int value,
    required String title,
    required int groupValue,
    required void Function(int) onChanged
  }) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onChanged(value);
      },
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          groupValue == value
              ? Icon(Icons.check_circle, color: ThemeVars.colorPrimary, size: 18,)
              : Icon(Icons.circle_outlined, color: ThemeVars.colorPrimary, size: 18,),
          SizedBox(width: 2,),
          Text(title, style: TextStyle(fontSize: 14),)
        ],
      ),
    );
  }

  Widget _renderFace() {
    if (_imageFile != null && _imageFile!.isNotEmpty) {
      return Row(
        children: List.generate(_imageFile!.length * 2 - 1, (index) {
          if (index.isOdd) {
            return SizedBox(width: 6,);
          }
          XFile item = _imageFile![index ~/ 2];
          return Image.file(
            File(item.path),
            fit: BoxFit.cover,
            width: 100,
            height: 100,
          );
        }),
      );
    }
    return Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: ThemeVars.colorBackground,
      ),
      child: const Icon(Icons.add, size: 50,),
    );
  }

  Future<void> _pickImage() async {
    final pickedImage = await _imagePicker.pickMultiImage();
    if (pickedImage != null && pickedImage.length > 3) {
      pickedImage.removeRange(3, pickedImage.length);
    }
    if (pickedImage != null && pickedImage.isNotEmpty) {
      setState(() {
        _imageFile = pickedImage;
      });
    }
  }

  @override
  void initState() {
    _imagePicker = ImagePicker();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "记账",
      child: Stack(
        children: [
          ListView(
            children: [
              MenuBlock(
                borderRadius: BorderRadius.circular(0),
                items: [
                  MenuBlockItem(
                      text: "收款对象",
                      prefix: _required,
                      showArrow: false,
                      suffix: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          _radio(
                            title: "租客",
                            value: 0,
                            groupValue: _collectedTarget,
                            onChanged: (value) => setState(() {
                              _collectedTarget = value;
                            }),
                          ),
                          SizedBox(width: 10,),
                          _radio(
                            title: "其他",
                            value: 1,
                            groupValue: _collectedTarget,
                            onChanged: (value) => setState(() {
                              _collectedTarget = value;
                            }),
                          )
                        ],
                      )
                  ),
                  if (_collectedTarget == 0) MenuBlockItem(
                      text: "选择租客",
                      prefix: _required,
                      suffix: _params["renterName"].isEmpty ? Text("请输入", style: TextStyle(color: ThemeVars.colorTextTer),) : Text(_params["renterName"]),
                      onTap: () {
                        Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                          return SelectRenter(onchange: (value) {
                            setState(() {
                              _params["renterName"] = value["renterName"];
                            });
                          },);
                        }));
                      }
                  ),
                  MenuBlockItem(
                      text: "收支",
                      prefix: _required,
                      suffix: _params["inoutFlag"] == null ? Text("请输入", style: TextStyle(color: ThemeVars.colorTextTer),) : Text(_params["inoutFlagName"]),
                      onTap: () async {
                        Map? popped = await showRoundedBottomSheet(
                          builder: (context) => BottomSheetSelect(
                            items: _inoutFlagList,
                            compare: (item) => item["value"] == _params["inoutFlag"],
                            itemAsString: (item) => item["name"],
                          ),
                        );
                        if (popped != null) {
                          setState(() {
                            _params["inoutFlag"] = popped["value"];
                            _params["inoutFlagName"] = popped["name"];
                          });
                        }
                      }
                  ),
                  if (_collectedTarget == 1) ...[
                    MenuBlockItem(
                        text: "姓名",
                        showArrow: false,
                        prefix: _required,
                        suffix: TextFormField(
                          initialValue: _params["renterName"],
                          textAlign: TextAlign.right,
                          decoration: const InputDecoration(
                            hintText: "请输入",
                            hintStyle: TextStyle(fontWeight: FontWeight.w100, color: ThemeVars.colorTextTer),
                            isDense: true,
                          ),
                          onChanged: (value) => setState(() {
                            _params["renterName"] = value;
                          }),
                        )
                    ),
                    MenuBlockItem(
                        text: "联系电话",
                        showArrow: false,
                        prefix: _required,
                        suffix: TextFormField(
                          initialValue: _params["contacts"],
                          textAlign: TextAlign.right,
                          maxLength: 11,
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                            hintText: "请输入",
                            hintStyle: TextStyle(fontWeight: FontWeight.w100, color: ThemeVars.colorTextTer),
                            isDense: true,
                            counterText: "",
                          ),
                          onChanged: (value) => setState(() {
                            _params["contacts"] = value;
                          }),
                        )
                    ),
                  ],
                  MenuBlockItem(
                      text: "费用名称",
                      showArrow: false,
                      prefix: _required,
                      suffix: TextFormField(
                        initialValue: _params["name"],
                        textAlign: TextAlign.right,
                        decoration: const InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(fontWeight: FontWeight.w100, color: ThemeVars.colorTextTer),
                          isDense: true,
                        ),
                        onChanged: (value) => setState(() {
                          _params["name"] = value;
                        }),
                      )
                  ),
                  MenuBlockItem(
                      text: "金额",
                      showArrow: false,
                      prefix: _required,
                      suffix: TextFormField(
                        initialValue: _params["money"],
                        textAlign: TextAlign.right,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          hintText: "请输入",
                          hintStyle: TextStyle(fontWeight: FontWeight.w100, color: ThemeVars.colorTextTer),
                          isDense: true,
                        ),
                        onChanged: (value) => setState(() {
                          _params["money"] = value;
                        }),
                      )
                  ),
                  MenuBlockItem(
                      text: "账单周期",
                      prefix: _required,
                      suffix: Text("${_params["billStartDate"]} - ${_params["billEndDate"]}"),
                      onTap: () {
                        showMultiDatePicker(
                            context: context,
                            type: DateTimeType.range,
                            startDate: DateTime.parse(_params["billStartDate"]),
                            endDate: DateTime.parse(_params["billEndDate"]),
                            onchange: (dateRange) {
                              setState(() {
                                _params["billStartDate"] = dateRange[0];
                                _params["billEndDate"] = dateRange[1];
                              });
                            }
                        );
                      }
                  ),
                  MenuBlockItem(
                      text: "待收日期",
                      prefix: _required,
                      suffix: Text(_params["noticeDate"]),
                      onTap: () {
                        showDatetimePicker(
                            context: context,
                            initialDateTime: DateTime.parse(_params["noticeDate"]),
                            onchange: (date) {
                              setState(() {
                                _params["noticeDate"] = DateTools.formatYMD(date);
                              });
                            }
                        );
                      }
                  ),
                  MenuBlockItem(
                      text: "账单备注",
                      suffix: _params["remark"].isEmpty ? Text("请填写", style: TextStyle(color: ThemeVars.colorTextTer),) : Text(_params["remark"]),
                      onTap: () async {
                        Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                          return EditRemark(remark: _params["remark"]);
                        },),).then((value) {
                          if (value != null) {
                            setState(() {
                              _params["remark"] = value;
                            });
                          }
                        });
                      }
                  ),
                  MenuBlockItem(
                      text: "凭证图片",
                      showArrow: false,
                      tip: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _renderFace(),
                          const Text("(限3张图片，单张图片不超过10M，仅支持PNG/JPG格式)", style: TextStyle(color: ThemeVars.colorWarning, fontSize: 12),)
                        ],
                      ),
                      // suffix: Icon(Icons.image_outlined),
                      onTap: _pickImage,
                  ),
                ],
              ),
            ],
          ),
          Positioned(
              left: 0,
              bottom: 30,
              width: MediaQuery.of(context).size.width,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
                child: Button(
                  type: ButtonType.primary,
                  child: Text("生成待收账单"),
                ),
              )
          )
        ],
      ),
    );
  }

}